/*
 *  Copyright (c) 2011 Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU Lesser Public License v2.1
 *  which accompanies this distribution, and is available at
 *  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 *  Contributors:
 *      Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany - RMI Client, FileChooser and WebDAV
 */
package de.ipk_gatersleben.bit.bi.edal.rmi.client.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.security.AccessControlException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import net.miginfocom.swing.MigLayout;

import org.jdesktop.swingx.JXTaskPaneContainer;

import de.ipk_gatersleben.bit.bi.edal.primary_data.file.EdalException;
import de.ipk_gatersleben.bit.bi.edal.primary_data.file.PrimaryDataDirectoryException;
import de.ipk_gatersleben.bit.bi.edal.primary_data.file.PrimaryDataEntityVersionException;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.DateEvents;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.EdalDate;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.EnumDublinCoreElements;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.MetaData;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.MetaDataException;
import de.ipk_gatersleben.bit.bi.edal.primary_data.metadata.UntypedData;
import de.ipk_gatersleben.bit.bi.edal.primary_data.security.EdalAuthenticateException;

import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientDataManager;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientPrimaryDataDirectory;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientPrimaryDataEntity;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientPrimaryDataEntityVersion;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientPrimaryDataFile;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.editor.MetaDataSaveDialog;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.CheckSumViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.DataFormatViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.DateEventsViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.IdentifierRelationViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.IdentifierViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.LanguageViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.LegalPersonInfoViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.MetadataViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.PersonInfoViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.SubjectViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.TextViewer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.gui.viewer.ViewerContainer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.Const;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.EdalAbstractFileFilter;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.EdalFileHelper;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.EdalTable;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.EdalTitleDialog;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.EdalTreeCellRenderer;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.InfiniteProgressPanel;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.JLinkLabel;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.JVersionLabel;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.LailapsJXTaskPane;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.MetaDescription;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.PrincipalUtil;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.StackTraceUtil;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.UiUtil;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.util.XStatusBar;

/**
 * <code>EDALFileChooser</code> provides a simple mechanism for the user to
 * choose a file from EDAL File System.
 * <p>
 * 
 * The following code pops up a file chooser for the user that sees only .jpg
 * and .gif images:
 * 
 * <pre>
 * EDALFileChooser chooser = new EDALFileChooser((Frame) window, rootDirectory);
 * EdalFileNameExtensionFilter filter = new EdalFileNameExtensionFilter(
 * 		&quot;JPG &amp; GIF Images&quot;, &quot;jpg&quot;, &quot;gif&quot;);
 * chooser.setFileFilter(filter);
 * int returnVal = chooser.showOpenDialog();
 * if (returnVal == EDALFileChooser.APPROVE_OPTION) {
 * 	System.out.println(&quot;You chose to open this file: &quot;
 * 			+ chooser.getSelectedFile().getName());
 * }
 * </pre>
 * <p>
 * 
 * @beaninfo attribute: isContainer false description: A component which allows
 *           for the interactive selection of a file.
 * 
 * @version 1.0
 * @author Jinbo Chen
 * 
 */

public class EdalFileChooser extends EdalTitleDialog {
	private static final long serialVersionUID = 1L;
	private static final Font FONT = new Font("Courier New", Font.PLAIN, 12);
	private DefaultTableModel defaultModel = null;
	private ClientPrimaryDataDirectory rootDirectory = null;
	private JTable filemetatable = null;
	private List<String> metadatatoshow = new ArrayList<String>();
	private List<ClientPrimaryDataEntity> filelist = new ArrayList<ClientPrimaryDataEntity>();
	private List<ClientPrimaryDataEntityVersion> versionlist = new ArrayList<ClientPrimaryDataEntityVersion>();
	private ClientPrimaryDataEntityVersion currentversion;
	private Map<String, ClientPrimaryDataEntityVersion> currentversionmap = new HashMap<String, ClientPrimaryDataEntityVersion>();
	private Map<String, JTextField> detailmap = new HashMap<String, JTextField>();
	private boolean bindui = false;
	private final JLabel pathlabel = new JLabel("Path:", JLabel.LEFT);
	protected final JTextField pathtext = new JTextField();
	protected ClientPrimaryDataEntity selectedFile = null;
	private final JTextField searchtext = new JTextField();
	protected ClientPrimaryDataDirectory currentdir;
	private DefaultMutableTreeNode currentnode;
	protected JButton okbutton;
	private int returnvalue;
	private int[] selectrows;
	private EdalAbstractFileFilter fileFilter = null;
	private int fileSelectionMode = FILES_ONLY;
	private boolean savemodal = false;
	private int fileselectindex;
	private String username = null;
	private static final String CHANGEMETADATAMETHODNAME = "setMetaData";
	private static final String CHANGEPERMISSIONTHODNAME = "grantPermission";
	private JSplitPane dirshowpane;
	private JSplitPane tableshowpane;
	private JPanel detailpanelparent;
	private JScrollPane treepanelparent;
	private LailapsJXTaskPane versionpanel;
	private LailapsJXTaskPane detailpanel;
	private JTree tree;
	private JButton configbutton = new JButton("eDAL Configration");
	private JButton metadatabutton = new JButton("ChangeMetadata");
	private JButton permissionbutton = new JButton("ChangePermissions");
	private Color tablebackcolor = null;
	private XStatusBar statusbar = null;
	private JPanel centerPane = new JPanel();
	private boolean isSelected = false;

	/**
	 * Return value if cancel is chosen.
	 */
	public static final int CANCEL_OPTION = 1;
	/**
	 * Return value if approve (yes, ok) is chosen.
	 */
	public static final int APPROVE_OPTION = 0;
	/**
	 * Return value if an error occured.
	 */
	public static final int ERROR_OPTION = -1;

	/** Instruction to display only files. */
	public static final int FILES_ONLY = 0;

	/** Instruction to display only directories. */
	public static final int DIRECTORIES_ONLY = 1;

	/** Instruction to display both files and directories. */
	public static final int FILES_AND_DIRECTORIES = 2;

	/** the max length of description and date */
	private static final int TEXTLIMIT = 40;
	/** the max length of tooltips */
	private static final int TOOLTIPSLEN = 20;
	/** the max length of metadata abstract */
	private static final int METADATALEN = 80;

	private boolean multiSelectionEnabled = false;
	private Map<String, String> tipsmap = new HashMap<String, String>();
	private int row;
	private int column;
	private ClientDataManager client = null;

	/**
	 * Constructs a <code>EDALFileChooser</code> that is initialized with
	 * <code>owner</code> as the swing container owner(JFrame),
	 * <code>rootDirectory</code> as the root directory, and <code>client</code>
	 * as the rmi client datamanager. If any of the parameters are
	 * <code>null</code> this method will not initialize.
	 * 
	 * @param owner
	 *            the swing container owner
	 * @param rootDirectory
	 *            the root directory
	 * @param client
	 *            the rmi client datamanager
	 */

	public EdalFileChooser(Frame owner, ClientDataManager client) {
		super(owner);
		if (client != null) {
			this.client = client;
			try {
				this.rootDirectory = client.getRootDirectory();
			} catch (RemoteException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (EdalAuthenticateException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane
						.showMessageDialog(
								null,
								"Can't login to Edal System,Please check your username and password!",
								Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}

			catch (NotBoundException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null, "No DataManager is bound!",
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			} catch (PrimaryDataDirectoryException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null,
						"Can't get Edal root directory!", Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (EdalException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			username = client.getAuthentication().getName();
			statusbar = new XStatusBar(client.getHost(), client.getPort(),
					username);
		}
	}

	/**
	 * Constructs a <code>EDALFileChooser</code> that is initialized with
	 * <code>owner</code> as the swing container owner(JDialog),
	 * <code>rootDirectory</code> as the root directory, and <code>client</code>
	 * as the rmi client datamanager. If any of the parameters are
	 * <code>null</code> this method will not initialize.
	 * 
	 * @param owner
	 *            the swing container owner
	 * @param rootDirectory
	 *            the root directory
	 * @param client
	 *            the rmi client datamanager
	 */
	public EdalFileChooser(Dialog owner, ClientDataManager client) {
		super(owner);
		if (client != null) {
			this.client = client;
			try {
				this.rootDirectory = client.getRootDirectory();
			} catch (RemoteException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (EdalAuthenticateException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane
						.showMessageDialog(
								null,
								"Can't login to Edal System,Please check your username and password!",
								Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}

			catch (NotBoundException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null, "No DataManager is bound!",
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			} catch (PrimaryDataDirectoryException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null,
						"Can't get Edal root directory!", Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (EdalException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			username = client.getAuthentication().getName();
			statusbar = new XStatusBar(client.getHost(), client.getPort(),
					username);
		}
	}

	/**
	 * Returns the selected file. This can be set by a user action, such as
	 * selecting the file from a list in the UI.
	 * 
	 * @return the selected file
	 */

	public ClientPrimaryDataEntity getSelectedFile() {
		if (!isSelected) {
			return null;
		}
		if (fileSelectionMode == DIRECTORIES_ONLY) {
			try {
				if (selectedFile.isDirectory()) {
					return selectedFile;
				}
			} catch (RemoteException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			return null;
		} else if (fileSelectionMode == FILES_ONLY) {
			try {
				if (!selectedFile.isDirectory()) {
					return selectedFile;
				}
			} catch (RemoteException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			return null;
		} else {
			if (selectedFile != null) {
				return selectedFile;
			} else {
				return currentdir;
			}
		}
	}

	private MetaData getEntityVersionMetaData(
			ClientPrimaryDataEntity dataentity,
			ClientPrimaryDataEntityVersion version) {
		try {
			Iterator<ClientPrimaryDataEntityVersion> it;
			it = dataentity.getVersions().iterator();
			while (it.hasNext()) {
				final ClientPrimaryDataEntityVersion curr = it.next();
				if (curr.getRevision().longValue() == version.getRevision()
						.longValue()) {
					return curr.getMetaData();
				}
			}
			return dataentity.getMetaData();
		} catch (RemoteException e) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		}
		return null;
	}

	/**
	 * Returns a list of selected files if the file chooser is set to allow
	 * multiple selection.
	 */

	public ClientPrimaryDataEntity[] getSelectedFiles() {
		if (selectrows != null && filelist.size() > 0) {
			if (fileSelectionMode == DIRECTORIES_ONLY) {
				ClientPrimaryDataEntity[] selectedFiles = new ClientPrimaryDataEntity[1];
				selectedFiles[0] = currentdir;
				return selectedFiles;
			} else if (fileSelectionMode == FILES_ONLY) {
				ClientPrimaryDataEntity[] selectedFiles = new ClientPrimaryDataEntity[selectrows.length];
				for (int i = 0; i < selectedFiles.length; i++) {
					selectedFiles[i] = filelist.get(selectrows[i]);
				}
				return selectedFiles;
			} else {
				ClientPrimaryDataEntity[] selectedFiles = new ClientPrimaryDataEntity[selectrows.length];
				for (int i = 0; i < selectedFiles.length; i++) {
					selectedFiles[i] = filelist.get(selectrows[i]);
				}
				return selectedFiles;
			}

		} else {
			if (fileSelectionMode == FILES_ONLY) {
				return new ClientPrimaryDataFile[0];
			} else {
				ClientPrimaryDataEntity[] selectedFiles = new ClientPrimaryDataEntity[1];
				selectedFiles[0] = currentdir;
				return selectedFiles;
			}
		}
	}

	/**
	 * Pops up an "Open File" file chooser dialog. Note that the text that
	 * appears in the approve button is determined by the L&F.
	 * 
	 * @return the return state of the file chooser on popdown:
	 *         <ul>
	 *         <li>EDALFileChooser.CANCEL_OPTION
	 *         <li>EDALFileChooser.APPROVE_OPTION
	 *         <li>EDALFileChooser.ERROR_OPTION if an error occurs or the dialog
	 *         is dismissed
	 *         </ul>
	 */

	public int showOpenDialog() {
		try {
			initViewers();
			savemodal = false;
			setTitle("Open File");
			init(rootDirectory);
			if (client == null) {
				if (CANCEL_OPTION == showlogindialog()) {
					dispose();
					return returnvalue;
				}
			}
			setModal(true);
			setLocationRelativeTo(null);
			setVisible(true);
			return returnvalue;
		} catch (Exception e) {
			dispose();
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(null, e.getMessage(),
					Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			return EdalFileChooser.ERROR_OPTION;
		}

	}

	/**
	 * Pops up a "Save File" file chooser dialog. Note that the text that
	 * appears in the approve button is determined by the L&F.
	 * 
	 * @return the return state of the file chooser on popdown:
	 *         <ul>
	 *         <li>EDALFileChooser.CANCEL_OPTION
	 *         <li>EDALFileChooser.APPROVE_OPTION
	 *         <li>EDALFileChooser.ERROR_OPTION if an error occurs or the dialog
	 *         is dismissed
	 *         </ul>
	 */

	public int showSaveDialog() {
		try {
			initViewers();
			savemodal = true;
			setTitle("Save File");
			init(rootDirectory);
			setModal(true);
			if (client == null) {
				if (CANCEL_OPTION == showlogindialog()) {
					dispose();
					return returnvalue;
				}
			}
			setLocationRelativeTo(null);
			setVisible(true);
			return returnvalue;
		} catch (Exception e) {
			dispose();
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(null, e.getMessage(),
					Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			return EdalFileChooser.ERROR_OPTION;
		}
	}

	/**
	 * Sets the file chooser to allow multiple file selections.
	 * 
	 * @param b
	 *            true if multiple files may be selected
	 * @beaninfo bound: true description: Sets multiple file selection mode.
	 */

	public void setMultiSelectionEnabled(boolean b) {
		multiSelectionEnabled = b;
	}

	/**
	 * Sets the current file filter. The file filter is used by the file chooser
	 * to filter out files from the user's view.
	 * 
	 * @beaninfo preferred: true bound: true description: Sets the File Filter
	 *           used to filter out files of type.
	 * 
	 * @param filter
	 *            the new current file filter to use
	 * @see #getFileFilter
	 */

	public void setFileFilter(EdalAbstractFileFilter filter) {
		this.fileFilter = filter;
	}

	/**
	 * Returns the currently selected file filter.
	 * 
	 * @return the current file filter
	 * @see #setFileFilter
	 */

	public EdalAbstractFileFilter getFileFilter() {
		return this.fileFilter;
	}

	/**
	 * Sets the <code>EDALFileChooser</code> to allow the user to just select
	 * files, just select directories, or select both files and directories. The
	 * default is <code>EDALFileChooser.FILES_ONLY</code>.
	 * 
	 * @param mode
	 *            the type of files to be displayed:
	 *            <ul>
	 *            <li>EDALFileChooser.FILES_ONLY
	 *            <li>EDALFileChooser.DIRECTORIES_ONLY
	 *            <li>EDALFileChooser.FILES_AND_DIRECTORIES
	 *            </ul>
	 * 
	 * @exception IllegalArgumentException
	 *                if <code>mode</code> is an illegal file selection mode
	 * @beaninfo preferred: true bound: true description: Sets the types of
	 *           files that the JFileChooser can choose. enum: FILES_ONLY
	 *           EDALFileChooser.FILES_ONLY DIRECTORIES_ONLY
	 *           EDALFileChooser.DIRECTORIES_ONLY
	 *           EDALFileChooser.FILES_AND_DIRECTORIES
	 * 
	 * 
	 * @see #getFileSelectionMode
	 */
	public void setFileSelectionMode(int mode) {
		if ((mode == FILES_ONLY) || (mode == DIRECTORIES_ONLY)
				|| (mode == FILES_AND_DIRECTORIES)) {
			fileSelectionMode = mode;
		} else {
			throw new IllegalArgumentException(
					"Incorrect Mode for file selection: " + mode);
		}
	}

	/**
	 * Returns the current file-selection mode. The default is
	 * <code>EDALFileChooser.FILES_ONLY</code>.
	 * 
	 * @return the type of files to be displayed, one of the following:
	 *         <ul>
	 *         <li>EDALFileChooser.FILES_ONLY
	 *         <li>EDALFileChooser.DIRECTORIES_ONLY
	 *         <li>EDALFileChooser.FILES_AND_DIRECTORIES
	 *         </ul>
	 * @see #setFileSelectionMode
	 */

	public int getFileSelectionMode() {
		return fileSelectionMode;
	}

	protected void init(ClientPrimaryDataDirectory rootDirectory) {
		currentdir = rootDirectory;

		// JPanel maincontents = (JPanel) getContentPane();
		JPanel maincontents = new JPanel();
		setContentPane(maincontents);

		maincontents.setLayout(new BorderLayout());

		maincontents.add(centerPane, BorderLayout.CENTER);
		maincontents.add(statusbar, BorderLayout.SOUTH);

		centerPane.removeAll();
		centerPane
				.setLayout(new MigLayout(
						"insets 1 1 1 10",
						"[7%!][5%!][9%!][36%!][5%!][2.8%!][22.1%!][1%!][2%!][7%!][1%!]",
						"[30!][grow,fill][30!][6!]"));

		if (rootDirectory != null) {
			pathlabel.setVerticalAlignment(JLabel.CENTER);
			pathlabel.setFont(FONT);
			centerPane.add(pathlabel, "cell 0 0 1 1");

			pathtext.setFont(FONT);
			centerPane.add(pathtext, "cell 1 0 4 1,width max(50%, 50%)");
		}

		searchtext.setFont(FONT);
		if (rootDirectory != null) {
			centerPane.add(searchtext, "cell 6 0 1 1,width max(35%, 35%)");
			searchtext.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					search(searchtext.getText().trim());
				}
			});
		}

		JButton searchbutton = new JButton(searchAction);
		searchbutton.setFont(FONT);
		if (rootDirectory != null) {
			centerPane.add(searchbutton, "cell 8 0 2 1");
		}

		detailpanelparent = new JPanel();
		detailpanelparent.setFont(FONT);
		detailpanelparent.setLayout(new BorderLayout());

		if (rootDirectory != null) {
			final ClientPrimaryDataDirectory f_rootDirectory = rootDirectory;
			tree = new JTree(addNodes(null, rootDirectory));
			EdalTreeCellRenderer renderer = new EdalTreeCellRenderer(
					tree.getCellRenderer());
			tree.setCellRenderer(renderer);
			tree.setOpaque(true);
			tree.setBackground(Color.white);
			UIDefaults treeDefaults = new UIDefaults();
			treeDefaults.put("Tree.selectionBackground", null);
			tree.putClientProperty("Nimbus.Overrides", treeDefaults);
			tree.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
			// final JScrollPane treepanelparent = new JScrollPane(tree);
			treepanelparent = new JScrollPane(tree);

			tree.addTreeSelectionListener(new TreeSelectionListener() {
				public void valueChanged(TreeSelectionEvent e) {
					isSelected = true;
					currentnode = (DefaultMutableTreeNode) e.getPath()
							.getLastPathComponent();
					treenodeclick(currentnode, f_rootDirectory);
				}
			});

			tree.addTreeWillExpandListener(new TreeWillExpandListenerAction(
					tree, rootDirectory));

			tree.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					// linux
					checktreeRightClick(e);
				}

				@Override
				public void mouseReleased(MouseEvent e) {
					// windows
					checktreeRightClick(e);
				}

				public void mouseClicked(MouseEvent e) {
					if (filemetatable != null) {
						filemetatable.clearSelection();

						final JTree ttree = (JTree) e.getComponent();
						TreePath tpath = ttree.getPathForLocation(e.getX(),
								e.getY());
						if (tpath != null
								&& tpath.getLastPathComponent() != null) {
							currentnode = (DefaultMutableTreeNode) tpath
									.getLastPathComponent();
							EdalNode mynode = (EdalNode) currentnode
									.getUserObject();
							pathtext.setText(mynode.getPath());
						}
					}
					treenodeclick(currentnode, f_rootDirectory);
				}

			});

			try {
				defaultModel = buildtable(rootDirectory
						.listPrimaryDataEntities());
			} catch (RemoteException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (PrimaryDataDirectoryException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(
						null,
						"Call Edal server function exception:"
								+ e1.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			filemetatable = new EdalTable(defaultModel);
			// filemetatable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

			if (multiSelectionEnabled) {
				filemetatable
						.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			} else {
				filemetatable
						.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			}

			filemetatable.getSelectionModel()
					.addListSelectionListener(
							new TableRowModelListener(filemetatable,
									detailpanelparent));

			filemetatable.addMouseMotionListener(new MouseMotionListener() {
				public void mouseDragged(MouseEvent e) {
				}

				public void mouseMoved(MouseEvent e) {
					Point point = e.getPoint();
					int x = filemetatable.rowAtPoint(point);
					int y = filemetatable.columnAtPoint(point);
					if (x != row || y != column) {
						row = x;
						column = y;
					}
					if (tipsmap.containsKey((row + 1) + "," + (column + 1))) {
						filemetatable.setToolTipText(formattooltips(tipsmap
								.get((row + 1) + "," + (column + 1))));
					} else if (row > 0 && column > 0) {
						Object tip = filemetatable.getValueAt(row, column);
						filemetatable.setToolTipText(formattooltips(tip
								.toString()));
					}
				}
			});

			filemetatable.addMouseListener(new MouseAdapter() {
				public void mousePressed(MouseEvent evt) {
					// linux
					checktableRightClick(evt, tree);
				}

				public void mouseReleased(MouseEvent evt) {
					// windows
					checktableRightClick(evt, tree);
				}
			});

			if (tablebackcolor == null) {
				tablebackcolor = filemetatable.getSelectionBackground();
			}

			/*
			 * 
			 * filemetatable.addFocusListener(new FocusListener(){ public void
			 * focusLost(FocusEvent e) { if (!e.isTemporary()) { //
			 * filemetatable.clearSelection(); //
			 * filemetatable.setSelectionBackground(new Color(135,206,250)); } }
			 * 
			 * @Override public void focusGained(FocusEvent e) {
			 * filemetatable.setSelectionBackground(tablebackcolor); } });
			 */

			tableshowpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
					new JScrollPane(filemetatable), detailpanelparent);
			UiUtil.fitTableColumns(filemetatable, 631);

			if (currentdir != null) {
				buildDetail(detailpanelparent, currentdir, true);
			}

			tableshowpane.setDividerLocation(0.75);
			tableshowpane.setResizeWeight(0.75);
			tableshowpane.resetToPreferredSizes();

			dirshowpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
					treepanelparent, tableshowpane);

			centerPane.add(dirshowpane, "cell 0 1 11 1,width max(100%, 100%)");

			detailpanelparent.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					// linux
					checkpanelRightClick(e);
				}

				@Override
				public void mouseReleased(MouseEvent e) {
					// windows
					checkpanelRightClick(e);
				}

			});
		}

		configbutton = new JButton(Const.CHANGECONN_BTN_STR);
		configbutton.setFont(FONT);

		configbutton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				showlogindialog();
			}
		});

		permissionbutton = new JButton(Const.CHANGEPERMISION_BTN_STR);
		permissionbutton.setFont(FONT);

		permissionbutton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				if (filelist.size() > 0
						&& filelist.get(fileselectindex) != null) {
					PermissionDialog permission = new PermissionDialog(filelist
							.get(fileselectindex), client);
					permission.showOpenDialog();
				} else {
					PermissionDialog permission = new PermissionDialog(
							currentdir, client);
					permission.showOpenDialog();
				}
			}
		});

		metadatabutton = new JButton(Const.CHANGEMETA_BTN_STR);
		metadatabutton.setFont(FONT);

		metadatabutton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				if (selectedFile != null) {
					MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
							selectedFile);
					int returnVal = metadlg.showOpenDialog();
					if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
						Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
								.getMetaDataValues();
						changemetadata(selectedFile, metadatavalue, false);
					}
				}
				/*
				 * if (filelist.size() > 0 && filelist.get(fileselectindex) !=
				 * null) { MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
				 * filelist.get(fileselectindex)); int returnVal =
				 * metadlg.showOpenDialog(); if (returnVal ==
				 * MetaDataSaveDialog.APPROVE_OPTION) {
				 * Map<EnumDublinCoreElements, UntypedData> metadatavalue =
				 * metadlg .getMetadatavalue();
				 * changemetadata(filelist.get(fileselectindex), metadatavalue,
				 * true); } } else { MetaDataSaveDialog metadlg = new
				 * MetaDataSaveDialog(currentdir); int returnVal =
				 * metadlg.showOpenDialog(); if (returnVal ==
				 * MetaDataSaveDialog.APPROVE_OPTION) {
				 * Map<EnumDublinCoreElements, UntypedData> metadatavalue =
				 * metadlg .getMetadatavalue(); changemetadata(currentdir,
				 * metadatavalue, false); } }
				 */
			}
		});

		okbutton = new JButton(Const.OK_BTN_STR);
		okbutton.setFont(FONT);

		okbutton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				if (getSelectedFile() == null) {
					return;
				}
				returnvalue = APPROVE_OPTION;
				dispose();
			}
		});

		JButton cancelbutton = new JButton(cancelAction);
		cancelbutton.setFont(FONT);

		JPanel functionButtons = new JPanel();
		functionButtons.setLayout(new FlowLayout(FlowLayout.RIGHT));
		functionButtons.add(configbutton);
		if (rootDirectory != null) {
			functionButtons.add(permissionbutton);
			functionButtons.add(metadatabutton);

			showmetabutton(rootDirectory);
			showpermissionbutton(rootDirectory);
		}
		functionButtons.add(okbutton);
		functionButtons.add(cancelbutton);

		JPanel buttons = new JPanel();
		buttons.setLayout(new BorderLayout());
		buttons.add(functionButtons, BorderLayout.EAST);

		centerPane.add(buttons, "cell 0 2 9 1,align right");
		addWindowListener(createAppCloser());

		this.setPreferredSize(new Dimension(950, 575));
		this.setMinimumSize(new Dimension(950, 575));

		if (rootDirectory != null) {
			this.addComponentListener(new ComponentAdapter() {
				public void componentResized(ComponentEvent e) {
					dirshowpane.setDividerLocation(0.3);
				}
			});
		}

		statusbar.updateStatus(client.getHost(), client.getPort(), username);
		maincontents.updateUI();
		this.pack();
		if (rootDirectory != null) {
			dirshowpane.setDividerLocation(0.3);
		}

	}

	private void treenodeclick(DefaultMutableTreeNode currentnode,
			ClientPrimaryDataDirectory f_rootDirectory) {
		if (currentnode == null || currentnode.getUserObject() == null) {
			return;
		}
		EdalNode mynode = (EdalNode) currentnode.getUserObject();
		pathtext.setText(mynode.getPath());
		cleartable();
		try {
			try {
				currentdir = (ClientPrimaryDataDirectory) EdalFileHelper
						.getEntity(mynode.getPath(), f_rootDirectory);
			} catch (PrimaryDataDirectoryException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null,
						"No such " + mynode.getPath() + " exists!",
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}
			List<ClientPrimaryDataEntity> dirlist = null;
			try {
				dirlist = currentdir.listPrimaryDataEntities();
			} catch (PrimaryDataDirectoryException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null, "Can't load load all "
						+ currentdir.getName() + "objects!",
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}
			if (dirlist != null) {
				defaultModel = buildtable(dirlist);
				filemetatable.setModel(defaultModel);
				defaultModel.fireTableDataChanged();
				UiUtil.fitTableColumns(filemetatable, 631);

				if (detailpanel != null) {
					if (!detailpanel.isCollapsed()) {
						detailpanel.setCollapsed(true);
						detailpanel.setScrollOnExpand(true);
					}
				}

			}
			if (currentdir != null) {
				buildDetail(detailpanelparent, currentdir, true);
			}
			showmetabutton(currentdir);
			showpermissionbutton(currentdir);
			// jinbo tree.scrollPathToVisible(e.getPath());
		} catch (RemoteException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e1.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		} catch (NotBoundException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(null,
					"Edal internal server error occurred:" + e1.getMessage(),
					Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
		}
	}

	private int showlogindialog() {

		EdalConfigDialog eDALConfigUi = new EdalConfigDialog();
		int returnVal = eDALConfigUi.showOpenDialog();
		if (returnVal == EdalConfigDialog.APPROVE_OPTION) {
			/*
			 * EdalLoginHelper helper = new EdalLoginHelper();
			 * helper.savedata(eDALConfigUi.getServeraddress(),
			 * eDALConfigUi.getServerport(), eDALConfigUi.getUsername(),
			 * eDALConfigUi.getPassword()); bindui = false; cleartable();
			 * init(EdalConfigDialog.rootDirectory); if (EdalConfigDialog.client
			 * != null) { client = EdalConfigDialog.client; username =
			 * client.getAuthentication().getName(); pathtext.setText(""); }
			 */
			return APPROVE_OPTION;

		}
		return CANCEL_OPTION;
	}

	@SuppressWarnings("unused")
	private void cleanbuttonevent(JButton button) {
		if (button != null) {
			for (ActionListener al : button.getActionListeners()) {
				button.removeActionListener(al);
			}
		}
	}

	private void checktableRightClick(MouseEvent evt, final JTree tree) {
		if (evt.isPopupTrigger()) {
			final int rightclickrow = evt.getY() / filemetatable.getRowHeight();

			JMenuItem del = new JMenuItem(Const.DEL_BTN_STR);
			JMenuItem rename = new JMenuItem(Const.RENAME_BTN_STR);
			JMenuItem permissionmenu = new JMenuItem(
					Const.CHANGEPERMISION_BTN_STR);

			JPopupMenu popupMenu;
			popupMenu = new JPopupMenu();

			if (savemodal) {
				popupMenu.add(del);
				popupMenu.add(rename);
			}

			if (filelist.size() > 0
					&& PrincipalUtil.checkPermission(currentdir, username,
							CHANGEPERMISSIONTHODNAME)
					&& filelist.get(rightclickrow) != null) {
				popupMenu.add(permissionmenu);
			}

			JMenuItem metadatamenu = new JMenuItem("Change Metadata");

			if (filelist.size() > 0 && filelist.get(fileselectindex) != null) {
				popupMenu.add(metadatamenu);
				if (!PrincipalUtil.checkPermission(
						filelist.get(fileselectindex), username,
						CHANGEMETADATAMETHODNAME)) {
					metadatamenu.setEnabled(false);
				}

			} else if (currentdir != null) {
				popupMenu.add(metadatamenu);
				if (!PrincipalUtil.checkPermission(currentdir, username,
						CHANGEMETADATAMETHODNAME)) {
					metadatamenu.setEnabled(false);
				}
			}

			metadatamenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (filelist.size() > 0
							&& filelist.get(fileselectindex) != null) {
						MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
								filelist.get(fileselectindex));
						int returnVal = metadlg.showOpenDialog();
						if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
							Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
									.getMetaDataValues();
							changemetadata(filelist.get(fileselectindex),
									metadatavalue, true);
						}
					} else {
						MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
								currentdir);
						int returnVal = metadlg.showOpenDialog();
						if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
							Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
									.getMetaDataValues();
							changemetadata(currentdir, metadatavalue, false);
						}
					}

				}
			});

			del.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					final String[] buttons = { "Yes", "No" };
					final int rc = JOptionPane.showOptionDialog(null,
							"Do you want to delete?", Const.EDAL_TITLE_STR,
							JOptionPane.INFORMATION_MESSAGE, 0, null, buttons,
							buttons[1]);
					if (rc == 0) {
						// delete current Directory or File
						try {
							if (filelist.size() > 0) {
								boolean shouldfresh = false;
								if (filelist.get(rightclickrow).isDirectory()) {
									shouldfresh = true;
								}

								filelist.get(rightclickrow).delete();
								filelist.remove(rightclickrow);

								List<ClientPrimaryDataEntity> dirlist = null;
								try {
									dirlist = currentdir
											.listPrimaryDataEntities();
								} catch (PrimaryDataDirectoryException e1) {
									ClientDataManager.logger
											.error(StackTraceUtil
													.getStackTrace(e1));
									JOptionPane.showMessageDialog(
											null,
											"Can't load load all "
													+ currentdir.getName()
													+ "objects!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								}
								if (dirlist != null) {
									defaultModel = buildtable(dirlist);
									filemetatable.setModel(defaultModel);
									defaultModel.fireTableDataChanged();
									UiUtil.fitTableColumns(filemetatable, 631);
								}
								if (shouldfresh) {
									refreshtreenode(tree);
								}
							}
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						} catch (PrimaryDataEntityVersionException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane
									.showMessageDialog(
											null,
											"The requested version is not available or marked as deleted!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
						} catch (PrimaryDataDirectoryException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(
									null,
									"Call Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			});

			rename.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String s = null;
					try {
						s = JOptionPane.showInputDialog(null,
								"Please input directoy name:",
								filelist.get(rightclickrow).getName());
					} catch (RemoteException e2) {
						ClientDataManager.logger.error(StackTraceUtil
								.getStackTrace(e2));
						JOptionPane
								.showMessageDialog(null,
										"Call remote Edal server function exception:"
												+ e2.getMessage(),
										Const.EDAL_TITLE_STR,
										JOptionPane.ERROR_MESSAGE);
					}
					if (s != null && s.trim().length() > 0) {
						// rename current directory
						try {
							try {
								if (currentdir.exist(s.trim())) {
									JOptionPane.showMessageDialog(
											null,
											"Error:["
													+ s.trim()
													+ "] already exists!\nPlease specify a different name.",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								} else {
									try {
										filelist.get(rightclickrow).rename(
												s.trim());
										List<ClientPrimaryDataEntity> dirlist = null;
										try {
											dirlist = currentdir
													.listPrimaryDataEntities();
										} catch (PrimaryDataDirectoryException e1) {
											ClientDataManager.logger
													.error(StackTraceUtil
															.getStackTrace(e1));
											JOptionPane.showMessageDialog(
													null,
													"Can't load load all "
															+ currentdir
																	.getName()
															+ "objects!",
													Const.EDAL_TITLE_STR,
													JOptionPane.ERROR_MESSAGE);
										}
										if (dirlist != null) {
											defaultModel = buildtable(dirlist);
											filemetatable
													.setModel(defaultModel);
											defaultModel.fireTableDataChanged();
											UiUtil.fitTableColumns(
													filemetatable, 631);
										}
										if (filelist.get(rightclickrow)
												.isDirectory()) {
											refreshtreenode(tree);
										}
									} catch (PrimaryDataEntityVersionException e1) {
										ClientDataManager.logger
												.error(StackTraceUtil
														.getStackTrace(e1));
										JOptionPane
												.showMessageDialog(
														null,
														"The requested version is not available or marked as deleted!",
														Const.EDAL_TITLE_STR,
														JOptionPane.ERROR_MESSAGE);
									}
								}
							} catch (PrimaryDataDirectoryException e1) {
								ClientDataManager.logger.error(StackTraceUtil
										.getStackTrace(e1));
								JOptionPane.showMessageDialog(
										null,
										"Can't load load all objects in "
												+ s.trim() + " directory!",
										Const.EDAL_TITLE_STR,
										JOptionPane.ERROR_MESSAGE);
							}
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			});

			permissionmenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					PermissionDialog permission = new PermissionDialog(filelist
							.get(rightclickrow), client);
					permission.showOpenDialog();
				}
			});

			popupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
		}
	}

	private void checktreeRightClick(MouseEvent e) {
		if (e.isPopupTrigger()) {
			final JTree tree = (JTree) e.getComponent();
			TreePath path = tree.getPathForLocation(e.getX(), e.getY());
			tree.setSelectionPath(path);

			JMenuItem del = new JMenuItem(Const.DELDIR_BTN_STR);
			JMenuItem rename = new JMenuItem(Const.RENAMEDIR_BTN_STR);
			JMenuItem newFile = new JMenuItem(Const.NEWDIR_BTN_STR);
			JMenuItem permissionmenu = new JMenuItem(
					Const.CHANGEPERMISION_BTN_STR);
			JMenuItem metadatamenu = new JMenuItem(Const.CHANGEMETA_BTN_STR);

			JPopupMenu popupMenu1;
			popupMenu1 = new JPopupMenu();

			if (savemodal) {
				if (currentnode != null) {
					popupMenu1.add(newFile);
				}

				if (path != null && path.getParentPath() != null) {
					// not root currentnode
					popupMenu1.add(del);
					popupMenu1.add(rename);
				}

			}

			if (currentnode != null) {
				if (PrincipalUtil.checkPermission(currentdir, username,
						CHANGEPERMISSIONTHODNAME)) {
					popupMenu1.add(permissionmenu);
				}
			}

			permissionmenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					PermissionDialog permission = new PermissionDialog(
							currentdir, client);
					permission.showOpenDialog();
				}
			});

			if (currentdir != null) {
				popupMenu1.add(metadatamenu);
				if (!PrincipalUtil.checkPermission(currentdir, username,
						CHANGEMETADATAMETHODNAME)) {
					metadatamenu.setEnabled(false);
				}
			}

			metadatamenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
							currentdir);
					int returnVal = metadlg.showOpenDialog();
					if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
						Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
								.getMetaDataValues();
						changemetadata(currentdir, metadatavalue, false);
					}
				}
			});

			del.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					final String[] buttons = { "Yes", "No" };
					final int rc = JOptionPane.showOptionDialog(null,
							"Do you want to delete current directory?",
							Const.EDAL_TITLE_STR,
							JOptionPane.INFORMATION_MESSAGE, 0, null, buttons,
							buttons[1]);
					if (rc == 0) {
						// delete current directory
						try {
							currentdir.delete();
							((DefaultMutableTreeNode) currentnode.getParent())
									.remove(currentnode);
							cleartable();
							tree.updateUI();
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						} catch (PrimaryDataEntityVersionException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane
									.showMessageDialog(
											null,
											"The requested version is not available or marked as deleted!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
						} catch (PrimaryDataDirectoryException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane
									.showMessageDialog(
											null,
											"Can't load load all objects in current directory!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			});

			newFile.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String s;
					s = JOptionPane
							.showInputDialog("Please input directoy name:");
					if (s != null && s.trim().length() > 0) {
						try {
							try {
								if (currentdir.exist(s.trim())) {
									JOptionPane
											.showMessageDialog(
													null,
													"Error:Directory ["
															+ s.trim()
															+ "] already exists!\nPlease specify a different name.",
													Const.EDAL_TITLE_STR,
													JOptionPane.ERROR_MESSAGE);
								} else if (s.indexOf("\\") >= 0
										|| s.indexOf("/") >= 0
										|| s.indexOf(":") >= 0
										|| s.indexOf("?") >= 0
										|| s.indexOf(">") >= 0
										|| s.indexOf("<") >= 0
										|| s.indexOf("|") >= 0
										|| s.indexOf("\"") >= 0
										|| s.indexOf("\\") >= 0) {
									JOptionPane
											.showMessageDialog(
													null,
													"Error:Directory name cannot contain any of the following characters:\\ / : * ? \" < > | !\nPlease specify a different name.",
													Const.EDAL_TITLE_STR,
													JOptionPane.ERROR_MESSAGE);
								} else {
									try {
										ClientPrimaryDataDirectory childdir = currentdir
												.createPrimaryDataDirectory(s
														.trim());
										// show modify metadata dialog
										Map<EnumDublinCoreElements, UntypedData> metadatavalue;
										MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
												childdir);
										int returnVal = metadlg
												.showOpenDialog();
										if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
											metadatavalue = metadlg
													.getMetaDataValues();
										} else {
											metadatavalue = null;
										}

										if (metadatavalue != null) {
											try {
												MetaData fileMetaData = childdir
														.getMetaData().clone();
												Iterator iter = metadatavalue
														.entrySet().iterator();
												while (iter.hasNext()) {
													Map.Entry<EnumDublinCoreElements, UntypedData> entry = (Map.Entry<EnumDublinCoreElements, UntypedData>) iter
															.next();
													EnumDublinCoreElements key = entry
															.getKey();
													UntypedData val = entry
															.getValue();
													fileMetaData
															.setElementValue(
																	key, val);
												}
												childdir.setMetaData(fileMetaData);
											} catch (Exception re) {
												ClientDataManager.logger.error(StackTraceUtil
														.getStackTrace(re));
												JOptionPane.showMessageDialog(
														null,
														re.getMessage(),
														Const.EDAL_TITLE_STR,
														JOptionPane.ERROR_MESSAGE);
											}
										}

										DefaultMutableTreeNode newChild = new EdalMutableTreeModel(
												new EdalNode(s.trim(), childdir
														.getPath()));

										currentnode.add(newChild);
										tree.updateUI();
										refreshtable();
									} catch (java.security.AccessControlException se) {
										ClientDataManager.logger
												.error(StackTraceUtil
														.getStackTrace(se));
										JOptionPane.showMessageDialog(
												null,
												"Can't create directory:"
														+ se.getMessage(),
												Const.EDAL_TITLE_STR,
												JOptionPane.ERROR_MESSAGE);
									}

								}
							} catch (PrimaryDataDirectoryException e1) {
								ClientDataManager.logger.error(StackTraceUtil
										.getStackTrace(e1));
								JOptionPane.showMessageDialog(
										null,
										"Can't load load all objects in "
												+ s.trim() + " directory!",
										Const.EDAL_TITLE_STR,
										JOptionPane.ERROR_MESSAGE);
							}
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			});

			rename.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String s = null;
					try {
						s = JOptionPane.showInputDialog(null,
								"Please input directoy name:",
								currentdir.getName());
					} catch (RemoteException e2) {
						ClientDataManager.logger.error(StackTraceUtil
								.getStackTrace(e2));
						JOptionPane
								.showMessageDialog(null,
										"Call remote Edal server function exception:"
												+ e2.getMessage(),
										Const.EDAL_TITLE_STR,
										JOptionPane.ERROR_MESSAGE);
					}
					if (s != null && s.trim().length() > 0) {
						// rename current directory
						try {
							try {
								if (currentdir.getParentDirectory().exist(
										s.trim())) {
									JOptionPane
											.showMessageDialog(
													null,
													"Error:Directory ["
															+ s.trim()
															+ "] already exists!\nPlease specify a different name.",
													Const.EDAL_TITLE_STR,
													JOptionPane.ERROR_MESSAGE);
								} else if (s.indexOf("\\") >= 0
										|| s.indexOf("/") >= 0
										|| s.indexOf(":") >= 0
										|| s.indexOf("?") >= 0
										|| s.indexOf(">") >= 0
										|| s.indexOf("<") >= 0
										|| s.indexOf("|") >= 0
										|| s.indexOf("\"") >= 0
										|| s.indexOf("\\") >= 0) {
									JOptionPane
											.showMessageDialog(
													null,
													"Error:Directory name cannot contain any of the following characters:\\ / : * ? \" < > | !\nPlease specify a different name.",
													Const.EDAL_TITLE_STR,
													JOptionPane.ERROR_MESSAGE);
								} else {
									try {
										currentdir.rename(s.trim());
										EdalNode mynode = (EdalNode) currentnode
												.getUserObject();
										mynode.setName(s.trim());
										mynode.setPath(currentdir.getPath());
										currentnode.setUserObject(mynode);
										tree.updateUI();
									} catch (PrimaryDataEntityVersionException e1) {
										ClientDataManager.logger
												.error(StackTraceUtil
														.getStackTrace(e1));
										JOptionPane
												.showMessageDialog(
														null,
														"The requested version is not available or marked as deleted!",
														Const.EDAL_TITLE_STR,
														JOptionPane.ERROR_MESSAGE);
									}
								}
							} catch (PrimaryDataDirectoryException e1) {
								ClientDataManager.logger.error(StackTraceUtil
										.getStackTrace(e1));
								JOptionPane.showMessageDialog(
										null,
										"Can't load load all objects in "
												+ s.trim() + " directory!",
										Const.EDAL_TITLE_STR,
										JOptionPane.ERROR_MESSAGE);
							}
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			});

			popupMenu1.show(tree, e.getX(), e.getY());
		}
	}

	private void checkpanelRightClick(MouseEvent e) {
		if (e.isPopupTrigger()) {

			final JPanel panel = (JPanel) e.getComponent();

			JMenuItem metadatamenu = new JMenuItem(Const.CHANGEMETA_BTN_STR);

			JPopupMenu popupMenu1;
			popupMenu1 = new JPopupMenu();

			if (filelist.size() > 0 && filelist.get(fileselectindex) != null) {
				if (!PrincipalUtil.checkPermission(
						filelist.get(fileselectindex), username,
						CHANGEMETADATAMETHODNAME)) {
					return;
				}
				popupMenu1.add(metadatamenu);
			} else if (currentdir != null) {
				if (!PrincipalUtil.checkPermission(currentdir, username,
						CHANGEMETADATAMETHODNAME)) {
					return;
				}
				popupMenu1.add(metadatamenu);
			}

			metadatamenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (filelist.size() > 0
							&& filelist.get(fileselectindex) != null) {
						MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
								filelist.get(fileselectindex));
						int returnVal = metadlg.showOpenDialog();
						if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
							Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
									.getMetaDataValues();
							changemetadata(filelist.get(fileselectindex),
									metadatavalue, true);
						}
					} else {
						MetaDataSaveDialog metadlg = new MetaDataSaveDialog(
								currentdir);
						int returnVal = metadlg.showOpenDialog();
						if (returnVal == MetaDataSaveDialog.APPROVE_OPTION) {
							Map<EnumDublinCoreElements, UntypedData> metadatavalue = metadlg
									.getMetaDataValues();
							changemetadata(currentdir, metadatavalue, false);
						}
					}

				}
			});

			popupMenu1.show(panel, e.getX(), e.getY());
		}
	}

	private void refreshtable() {
		cleartable();
		List<ClientPrimaryDataEntity> dirlist = null;
		try {
			dirlist = currentdir.listPrimaryDataEntities();
		} catch (PrimaryDataDirectoryException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(null,
					"Can't load load all current objects!",
					Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
		} catch (RemoteException e) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		}
		if (dirlist != null) {
			defaultModel = buildtable(dirlist);
			filemetatable.setModel(defaultModel);
			defaultModel.fireTableDataChanged();
			UiUtil.fitTableColumns(filemetatable, 631);
		}
	}

	private void refreshtreenode(JTree tree) {
		if (currentnode != null) {
			currentnode.removeAllChildren();
			if (currentdir != null) {
				try {
					List<ClientPrimaryDataEntity> dirlist = currentdir
							.listPrimaryDataEntities();
					List<String> dirnamelist = new ArrayList<String>();
					final Map<String, ClientPrimaryDataEntity> dirnamemap = new HashMap<String, ClientPrimaryDataEntity>();

					if (dirlist != null) {
						for (ClientPrimaryDataEntity dir : dirlist) {
							if (dir.isDirectory()
									&& !(dir.getCurrentVersion().isDeleted())) {
								dirnamelist.add(dir.getName());
								dirnamemap.put(dir.getName(), dir);
							}
						}
					}
					Collections
							.sort(dirnamelist, String.CASE_INSENSITIVE_ORDER);

					for (final String dirname : dirnamelist) {
						DefaultMutableTreeNode child = new EdalMutableTreeModel(
								new EdalNode(
										dirname,
										((ClientPrimaryDataDirectory) dirnamemap
												.get(dirname)).getPath()));
						currentnode.add(child);
					}
					tree.updateUI();
				} catch (RemoteException e1) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e1));
					JOptionPane.showMessageDialog(
							null,
							"Call remote Edal server function exception:"
									+ e1.getMessage(), Const.EDAL_TITLE_STR,
							JOptionPane.ERROR_MESSAGE);
				} catch (PrimaryDataDirectoryException e1) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e1));
					JOptionPane
							.showMessageDialog(
									null,
									"Can't load load all objects in current directory!",
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}

	protected void initViewers() {
		// EditorContainer.clear();
		metadatatoshow.add("DATE");
		metadatatoshow.add("FORMAT");
		ViewerContainer.registerViewer(EnumDublinCoreElements.CHECKSUM,
				new CheckSumViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.CREATOR,
				new PersonInfoViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.CONTRIBUTOR,
				new PersonInfoViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.PUBLISHER,
				new LegalPersonInfoViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.RELATION,
				new IdentifierRelationViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.DATE,
				new DateEventsViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.COVERAGE,
				new TextViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.DESCRIPTION,
				new TextViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.FORMAT,
				new DataFormatViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.IDENTIFIER,
				new IdentifierViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.LANGUAGE,
				new LanguageViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.RIGHTS,
				new TextViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.SOURCE,
				new TextViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.SUBJECT,
				new SubjectViewer());
		ViewerContainer.registerViewer(EnumDublinCoreElements.TITLE,
				new TextViewer());

	}

	private void switchversion(int versionidx) {
		if (selectedFile != null) {
			currentversion = versionlist.get(versionidx);
			try {
				String strdate = null;
				SimpleDateFormat dataformat = new SimpleDateFormat(
						"yyyy/MM/dd HH:mm:ss");
				if (currentversion.getRevisionDate() != null) {
					strdate = dataformat.format(currentversion
							.getRevisionDate().getTime());
				}
				selectedFile.switchCurrentVersion(currentversion);
				currentversionmap.put(selectedFile.getPath(), currentversion);
				versionpanel.setTitle("Version:" + currentversion.getRevision()
						+ " from " + strdate
						+ (currentversion.isDeleted() ? " - deleted." : ""));

			} catch (RemoteException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			} catch (AccessControlException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			} catch (PrimaryDataEntityVersionException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			}
		}
	}

	private Action cancelAction = new AbstractAction(Const.CANCEL_BTN_STR) {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			selectedFile = null;
			returnvalue = CANCEL_OPTION;
			dispose();
		}
	};

	private Action searchAction = new AbstractAction(Const.SEARCH_BTN_STR) {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			search(searchtext.getText().trim());
		}
	};
	private JXTaskPaneContainer metainfocontainer;

	private void search(final String keyword) {
		cleartable();

		final Set<ClientPrimaryDataEntity> results = new HashSet<ClientPrimaryDataEntity>();
		final List<ClientPrimaryDataEntity> resultslist = new ArrayList<ClientPrimaryDataEntity>();

		if (currentdir == null) {
			currentdir = rootDirectory;
		}

		final EdalFileChooser thisdialog = this;
		final Cursor cursor = thisdialog.getCursor();
		thisdialog.setCursor(new Cursor(Cursor.WAIT_CURSOR));
		final InfiniteProgressPanel glassPane = new InfiniteProgressPanel();
		glassPane.setWidth(this.getWidth());
		glassPane.setHeight(this.getHeight() - 150);
		this.setGlassPane(glassPane);
		glassPane.setText("search for:" + keyword);
		glassPane.start();

		new Thread() {
			public void run() {
				try {
					ClientPrimaryDataEntity[] result = currentdir
							.searchByKeyword(keyword, true, true).toArray(
									new ClientPrimaryDataEntity[0]);
					if (result != null) {
						for (ClientPrimaryDataEntity data : result) {
							results.add(data);
						}
					}

					for (ClientPrimaryDataEntity data : results) {
						resultslist.add(data);
					}

					defaultModel = buildtable(resultslist);
					filemetatable.setModel(defaultModel);
					defaultModel.fireTableDataChanged();
					UiUtil.fitTableColumns(filemetatable, 631);
				} catch (RemoteException e) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e));
					JOptionPane.showMessageDialog(
							null,
							"Call remote Edal server function exception:"
									+ e.getMessage(), Const.EDAL_TITLE_STR,
							JOptionPane.ERROR_MESSAGE);
				} catch (final PrimaryDataDirectoryException e) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e));
					JOptionPane.showMessageDialog(null,
							"Can't find object or there are too much results!",
							Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
				} finally {
					thisdialog.setCursor(cursor);
					glassPane.stop();
				}
			}
		}.start();

	}

	private void cleartable() {
		if (defaultModel != null) {
			int irow = defaultModel.getRowCount();
			for (int i = 0; i < irow; i++) {
				defaultModel.removeRow(0);
			}
		}
		filelist.clear();
		selectedFile = null;
	}

	private EdalTableModel buildtable(List<ClientPrimaryDataEntity> dirlist) {
		tipsmap.clear();
		row = 0;
		column = 0;

		List<String> columnlist = new ArrayList<String>();
		columnlist.add("TITLE");

		for (EnumDublinCoreElements elem : EnumDublinCoreElements.values()) {
			String dataName = elem.toString();
			if (metadatatoshow.contains(dataName)) {
				columnlist.add(dataName);
			}
		}

		final Object[] columnNames = columnlist.toArray(new String[0]);

		List<List<String>> datalist = new ArrayList<List<String>>();

		if (dirlist != null) {
			Collections.sort(dirlist);
			for (ClientPrimaryDataEntity dataentry : dirlist) {
				try {
					try {
						dataentry.getCurrentVersion();
					} catch (Exception e) {
						continue;
					}
					if (dataentry.getCurrentVersion().isDeleted()) {
						continue;
					}
				} catch (RemoteException e1) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e1));
					JOptionPane.showMessageDialog(
							null,
							"Call remote Edal server function exception:"
									+ e1.getMessage(), Const.EDAL_TITLE_STR,
							JOptionPane.ERROR_MESSAGE);
				}

				if (fileSelectionMode == FILES_AND_DIRECTORIES) {
					try {
						if (!dataentry.isDirectory()
								&& (fileFilter == null || fileFilter
										.accept((ClientPrimaryDataFile) dataentry))) {
							List<String> rowlist = new ArrayList<String>();

							rowlist.add(dataentry.getName());

							MetaData filemetadata = dataentry
									.getCurrentVersion().getMetaData();
							for (EnumDublinCoreElements elem : EnumDublinCoreElements
									.values()) {
								String dataName = elem.toString();
								try {
									if (metadatatoshow.contains(dataName)) {
										if ("DATE".equals(dataName)) {
											String tvalue = null;
											DateEvents tdataevents = (DateEvents) filemetadata
													.getElementValue(elem);
											Set<EdalDate> dataset = tdataevents
													.getSet();
											for (EdalDate edaldate : dataset) {
												if ("UPDATED".equals(edaldate
														.getEvent())) {
													tvalue = edaldate
															.toString();
													break;
												}
											}
											if (tvalue == null) {
												for (EdalDate edaldate : dataset) {
													if ("CREATED"
															.equals(edaldate
																	.getEvent())) {
														tvalue = edaldate
																.toString();
														break;
													}
												}
											}
											rowlist.add(tvalue);
										} else {
											String value = filemetadata
													.getElementValue(elem)
													.toString();
											if (value != null
													&& value.length() > TEXTLIMIT) {
												int itemprow = datalist.size() + 1;
												int itempcol = rowlist.size() + 1;
												tipsmap.put(itemprow + ","
														+ itempcol, value);
												rowlist.add(value.substring(0,
														TEXTLIMIT) + "...");
											} else {
												rowlist.add(value);
											}
										}

									}
								} catch (MetaDataException e) {
									ClientDataManager.logger
											.error(StackTraceUtil
													.getStackTrace(e));
									JOptionPane.showMessageDialog(null,
											"Can't load the value for "
													+ dataName + "!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								}
							}

							datalist.add(rowlist);

							filelist.add(dataentry);
						} else if (dataentry.isDirectory()) {
							List<String> rowlist = new ArrayList<String>();

							rowlist.add(dataentry.getName());

							MetaData filemetadata = dataentry
									.getCurrentVersion().getMetaData();
							for (EnumDublinCoreElements elem : EnumDublinCoreElements
									.values()) {
								String dataName = elem.toString();
								try {
									if (metadatatoshow.contains(dataName)) {
										if ("DATE".equals(dataName)) {
											String tvalue = null;
											DateEvents tdataevents = (DateEvents) filemetadata
													.getElementValue(elem);
											Set<EdalDate> dataset = tdataevents
													.getSet();
											for (EdalDate edaldate : dataset) {
												if ("UPDATED".equals(edaldate
														.getEvent())) {
													tvalue = edaldate
															.toString();
													break;
												}
											}
											if (tvalue == null) {
												for (EdalDate edaldate : dataset) {
													if ("CREATED"
															.equals(edaldate
																	.getEvent())) {
														tvalue = edaldate
																.toString();
														break;
													}
												}
											}
											rowlist.add(tvalue);
										} else {
											String value = filemetadata
													.getElementValue(elem)
													.toString();
											if (value != null
													&& value.length() > TEXTLIMIT) {
												int itemprow = datalist.size() + 1;
												int itempcol = rowlist.size() + 1;
												tipsmap.put(itemprow + ","
														+ itempcol, value);
												rowlist.add(value.substring(0,
														TEXTLIMIT) + "...");
											} else {
												rowlist.add(value);
											}
										}

									}
								} catch (MetaDataException e) {
									ClientDataManager.logger
											.error(StackTraceUtil
													.getStackTrace(e));
									JOptionPane.showMessageDialog(null,
											"Can't load the value for "
													+ dataName + "!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								}
							}

							datalist.add(rowlist);

							filelist.add(dataentry);
						}
					} catch (RemoteException e) {
						ClientDataManager.logger.error(StackTraceUtil
								.getStackTrace(e));
						JOptionPane.showMessageDialog(null,
								"Call remote Edal server function exception:"
										+ e.getMessage(), Const.EDAL_TITLE_STR,
								JOptionPane.ERROR_MESSAGE);
					}
				} else if (fileSelectionMode == DIRECTORIES_ONLY) {
					try {
						if (dataentry.isDirectory()) {
							List<String> rowlist = new ArrayList<String>();

							rowlist.add(dataentry.getName());

							MetaData filemetadata = dataentry
									.getCurrentVersion().getMetaData();
							for (EnumDublinCoreElements elem : EnumDublinCoreElements
									.values()) {
								String dataName = elem.toString();
								try {
									if (metadatatoshow.contains(dataName)) {
										if ("DATE".equals(dataName)) {
											String tvalue = null;
											DateEvents tdataevents = (DateEvents) filemetadata
													.getElementValue(elem);
											Set<EdalDate> dataset = tdataevents
													.getSet();
											for (EdalDate edaldate : dataset) {
												if ("UPDATED".equals(edaldate
														.getEvent())) {
													tvalue = edaldate
															.toString();
													break;
												}
											}
											if (tvalue == null) {
												for (EdalDate edaldate : dataset) {
													if ("CREATED"
															.equals(edaldate
																	.getEvent())) {
														tvalue = edaldate
																.toString();
														break;
													}
												}
											}
											rowlist.add(tvalue);
										} else {
											String value = filemetadata
													.getElementValue(elem)
													.toString();
											if (value != null
													&& value.length() > TEXTLIMIT) {
												int itemprow = datalist.size() + 1;
												int itempcol = rowlist.size() + 1;
												tipsmap.put(itemprow + ","
														+ itempcol, value);
												rowlist.add(value.substring(0,
														TEXTLIMIT) + "...");
											} else {
												rowlist.add(value);
											}
										}

									}
								} catch (MetaDataException e) {
									ClientDataManager.logger
											.error(StackTraceUtil
													.getStackTrace(e));
									JOptionPane.showMessageDialog(null,
											"Can't load the value for "
													+ dataName + "!",
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								}
							}

							datalist.add(rowlist);

							filelist.add(dataentry);
						}
					} catch (RemoteException e) {
						ClientDataManager.logger.error(StackTraceUtil
								.getStackTrace(e));
						JOptionPane.showMessageDialog(null,
								"Call remote Edal server function exception:"
										+ e.getMessage(), Const.EDAL_TITLE_STR,
								JOptionPane.ERROR_MESSAGE);
					}
				} else if (fileSelectionMode == FILES_ONLY) {
					try {
						if (!dataentry.isDirectory()
								&& (fileFilter == null || fileFilter
										.accept((ClientPrimaryDataFile) dataentry))) {
							List<String> rowlist = new ArrayList<String>();

							rowlist.add(dataentry.getName());

							MetaData filemetadata = dataentry
									.getCurrentVersion().getMetaData();
							for (EnumDublinCoreElements elem : EnumDublinCoreElements
									.values()) {
								try {
									String dataName = elem.toString();
									if (metadatatoshow.contains(dataName)) {
										String value = filemetadata
												.getElementValue(elem)
												.toString();
										if ("DATE".equals(dataName)) {
											String tvalue = null;
											DateEvents tdataevents = (DateEvents) filemetadata
													.getElementValue(elem);
											Set<EdalDate> dataset = tdataevents
													.getSet();
											for (EdalDate edaldate : dataset) {
												if ("UPDATED".equals(edaldate
														.getEvent())) {
													tvalue = edaldate
															.toString();
													break;
												}
											}
											if (tvalue == null) {
												for (EdalDate edaldate : dataset) {
													if ("CREATED"
															.equals(edaldate
																	.getEvent())) {
														tvalue = edaldate
																.toString();
														break;
													}
												}
											}
											rowlist.add(tvalue);
										} else {
											if (value != null
													&& value.length() > TEXTLIMIT) {
												int itemprow = datalist.size() + 1;
												int itempcol = rowlist.size() + 1;
												tipsmap.put(itemprow + ","
														+ itempcol, value);
												rowlist.add(value.substring(0,
														TEXTLIMIT) + "...");
											} else {
												rowlist.add(value);
											}
										}
									}
								} catch (MetaDataException e) {
									ClientDataManager.logger
											.error(StackTraceUtil
													.getStackTrace(e));
									JOptionPane.showMessageDialog(
											null,
											"Metadata operate Exception:"
													+ e.getMessage(),
											Const.EDAL_TITLE_STR,
											JOptionPane.ERROR_MESSAGE);
								}
							}

							datalist.add(rowlist);

							filelist.add(dataentry);
						}
					} catch (RemoteException e) {
						ClientDataManager.logger.error(StackTraceUtil
								.getStackTrace(e));
						JOptionPane.showMessageDialog(null,
								"Call remote Edal server function exception:"
										+ e.getMessage(), Const.EDAL_TITLE_STR,
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		}

		Object[][] rowData = new Object[datalist.size()][columnNames.length];
		for (int i = 0; i < datalist.size(); i++) {
			List<String> rowlist = datalist.get(i);
			for (int j = 0; j < rowlist.size(); j++) {
				rowData[i][j] = rowlist.get(j);
			}
		}

		return new EdalTableModel(rowData, columnNames);

	}

	private void showmetabutton(ClientPrimaryDataEntity dataentry) {
		if (!PrincipalUtil.checkPermission(dataentry, username,
				CHANGEMETADATAMETHODNAME)) {
			metadatabutton.setVisible(false);
		} else {
			metadatabutton.setVisible(true);
		}
	}

	private void showpermissionbutton(ClientPrimaryDataEntity dataentry) {
		if (!PrincipalUtil.checkPermission(dataentry, username,
				CHANGEPERMISSIONTHODNAME)) {
			permissionbutton.setVisible(false);
		} else {
			permissionbutton.setVisible(true);
		}
	}

	private void buildDetail(JPanel detailpanelparent,
			ClientPrimaryDataEntity dataentry, boolean refreshversion) {
		showmetabutton(dataentry);
		showpermissionbutton(dataentry);

		List<String> columnlist = new ArrayList<String>();

		for (EnumDublinCoreElements elem : EnumDublinCoreElements.values()) {
			try {
				String dataName = elem.toString();
				columnlist.add(dataName);
			} catch (UnsupportedOperationException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(null,
						"UnsupportedOperation Exception!",
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}
		}

		final Object[] columnNames = columnlist.toArray(new String[0]);

		int ilen = columnNames.length;

		int columnlen = ilen / 2;

		if (columnlen * 2 < ilen) {
			columnlen++;
		}

		if (!bindui) {
			metainfocontainer = new JXTaskPaneContainer();
			metainfocontainer.setBackground(new Color(238, 238, 238));

			detailpanel = new LailapsJXTaskPane();
			detailpanel.setBackground(new Color(238, 238, 238));
			detailpanel.setJSplitPane(tableshowpane);

			detailpanel.setName("Metadata Information");
			String metaabstract;
			try {
				metaabstract = dataentry.getMetaData().toString();
				if (metaabstract.length() > METADATALEN) {
					metaabstract = metaabstract.substring(0, METADATALEN)
							+ "...";
				}
				detailpanel.setTitle("Meta data:" + metaabstract);
			} catch (RemoteException e1) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(e1));
				JOptionPane.showMessageDialog(null, e1.getMessage(),
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}

			if (!detailpanel.isCollapsed()) {
				detailpanel.setCollapsed(true);
				detailpanel.setScrollOnExpand(true);
			}

			detailpanel.removeAll();
			detailpanel.setLayout(new MigLayout("",
					"[16%!][32%!][16%!][31%!][4%!]", ""));

			for (int i = 0; i < columnlen; i++) {
				JLabel label1 = new JLinkLabel(columnNames[i * 2].toString()
						+ ":", JLabel.LEFT);
				label1.setVerticalAlignment(JLabel.CENTER);
				label1.setFont(FONT);
				label1.setToolTipText("<html>"
						+ MetaDescription.getDescription(columnNames[i * 2]
								.toString()) + "</html>");
				detailpanel.add(label1, "cell 0 " + i + " 1 1");

				JTextField text1 = new JTextField();
				text1.setFont(FONT);
				detailpanel.add(text1, "cell 1 " + i + " 1 1,growx");
				detailmap.put(columnNames[i * 2].toString(), text1);

				if (i * 2 + 1 < columnNames.length) {
					JLabel label2 = new JLinkLabel(
							columnNames[i * 2 + 1].toString() + ":",
							JLabel.LEFT);
					label2.setVerticalAlignment(JLabel.CENTER);
					label2.setFont(FONT);
					label2.setToolTipText("<html>"
							+ MetaDescription
									.getDescription(columnNames[i * 2 + 1]
											.toString()) + "</html>");
					detailpanel.add(label2, "cell 2 " + i + " 1 1");

					JTextField text2 = new JTextField();
					text2.setFont(FONT);
					detailpanel.add(text2, "cell 3 " + i + " 1 1,growx");
					detailmap.put(columnNames[i * 2 + 1].toString(), text2);
				}

			}
			metainfocontainer.add(detailpanel);
			SortedSet<ClientPrimaryDataEntityVersion> versions;
			try {
				versions = dataentry.getVersions();
				if (versions != null) {
					ClientPrimaryDataEntityVersion[] versionarray = versions
							.toArray(new ClientPrimaryDataEntityVersion[0]);
					versionpanel = new LailapsJXTaskPane();
					// versionpanel.setBackground(new Color(238,238,238));
					buidversionpanel(versionpanel, versionarray);

					metainfocontainer.add(versionpanel);
				}

			} catch (RemoteException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
			detailpanelparent.add(new JScrollPane(metainfocontainer),
					BorderLayout.CENTER);

			bindui = true;
		}
		String metaabstract;
		try {
			metaabstract = dataentry.getMetaData().toString();
			if (metaabstract.length() > METADATALEN) {
				metaabstract = metaabstract.substring(0, METADATALEN) + "...";
			}
			detailpanel.setTitle("Meta data:" + metaabstract);
		} catch (RemoteException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(null, e1.getMessage(),
					Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
		}
		// bind event to ui
		MetaData filemetadata;
		try {
			if (currentversionmap.containsKey(dataentry.getPath())) {
				filemetadata = getEntityVersionMetaData(dataentry,
						currentversionmap.get(dataentry.getPath()));
			} else {
				filemetadata = dataentry.getCurrentVersion().getMetaData();
			}
			for (final EnumDublinCoreElements elem : EnumDublinCoreElements
					.values()) {
				final String dataName = elem.toString();
				try {
					final UntypedData data = filemetadata.getElementValue(elem);

					if (detailmap.containsKey(dataName)) {
						final MetadataViewer viewer = ViewerContainer
								.getViewer(EnumDublinCoreElements
										.valueOf(dataName));
						if (viewer != null) {
							for (MouseListener al : detailmap.get(dataName)
									.getMouseListeners()) {
								detailmap.get(dataName).removeMouseListener(al);
							}
							detailmap.get(dataName).addMouseListener(
									new MouseAdapter() {
										public void mouseClicked(MouseEvent e) {
											if (e.getClickCount() == 2) {
												viewer.setValue(data);
												viewer.setTitle(dataName
														+ " Information");
												viewer.showOpenDialog();
											}
										}
									});
							continue;
						}
						detailmap.get(dataName).setEditable(false);
					}
				} catch (MetaDataException e) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e));
					JOptionPane.showMessageDialog(null,
							"Can't load the value for " + dataName + "!",
							Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
				}
			}
		} catch (RemoteException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e1.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		}
		// bind value to ui

		try {
			if (currentversionmap.containsKey(dataentry.getPath())) {
				filemetadata = getEntityVersionMetaData(dataentry,
						currentversionmap.get(dataentry.getPath()));
			} else {
				filemetadata = dataentry.getCurrentVersion().getMetaData();
			}

			for (EnumDublinCoreElements elem : EnumDublinCoreElements.values()) {
				String dataName = elem.toString();
				try {
					final UntypedData data = filemetadata.getElementValue(elem);
					String value = data.toString();
					if (detailmap.containsKey(dataName)) {
						detailmap.get(dataName).setText(value);
						detailmap.get(dataName).setCaretPosition(0);
						if (value.trim().length() > 0) {
							detailmap.get(dataName).setToolTipText(
									formattooltips(value));
						}
					}
				} catch (MetaDataException e) {
					ClientDataManager.logger.error(StackTraceUtil
							.getStackTrace(e));
					JOptionPane.showMessageDialog(null,
							"Can't load the value for " + dataName + "!",
							Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
				}
			}
		} catch (RemoteException e1) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e1));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e1.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		}

		selectedFile = dataentry;

		if (refreshversion) {
			SortedSet<ClientPrimaryDataEntityVersion> versions;
			try {
				versions = dataentry.getVersions();
				versionlist.clear();
				if (versions != null) {
					ClientPrimaryDataEntityVersion[] versionarray = versions
							.toArray(new ClientPrimaryDataEntityVersion[0]);
					buidversionpanel(versionpanel, versionarray);
				}

			} catch (RemoteException e) {
				ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
				JOptionPane.showMessageDialog(
						null,
						"Call remote Edal server function exception:"
								+ e.getMessage(), Const.EDAL_TITLE_STR,
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private class LinkMouseListener extends MouseAdapter {
		private int versionidx;
		private JPanel detailpanelparent;
		private List<JVersionLabel> versionbuttonlist;

		public LinkMouseListener(List<JVersionLabel> versionbuttonlist,
				int versionidx, JPanel detailpanelparent) {
			this.versionidx = versionidx;
			this.detailpanelparent = detailpanelparent;
			this.versionbuttonlist = versionbuttonlist;
		}

		@Override
		public void mouseClicked(java.awt.event.MouseEvent evt) {
			if (versionbuttonlist != null) {
				for (int i = 0; i < versionbuttonlist.size(); i++) {
					if (i != versionidx) {
						versionbuttonlist.get(i).setSelect(false);
					} else {
						versionbuttonlist.get(i).setSelect(true);
					}
				}
			}
			switchversion(versionidx);
			if (filelist.size() > 0 && filelist.get(fileselectindex) != null) {
				buildDetail(detailpanelparent, filelist.get(fileselectindex),
						false);
			} else {
				buildDetail(detailpanelparent, selectedFile, false);
			}
		}
	}

	private void buidversionpanel(LailapsJXTaskPane versionpanel,
			ClientPrimaryDataEntityVersion[] versionarray)
			throws RemoteException {
		versionpanel.setJSplitPane(tableshowpane);
		versionpanel.setFriendpanel(detailpanel);
		detailpanel.setFriendpanel(versionpanel);
		versionpanel.setName("Version Information");
		versionpanel.setTitle("Version Information");
		if (!versionpanel.isCollapsed()) {
			versionpanel.setCollapsed(true);
			versionpanel.setScrollOnExpand(true);
		}

		int iversionlen = versionarray.length;

		int versioncolumnlen = iversionlen / 2;

		if (versioncolumnlen * 2 < iversionlen) {
			versioncolumnlen++;
		}

		List<JVersionLabel> versionbuttonlist = new ArrayList<JVersionLabel>();

		versionpanel.removeAll();
		versionpanel.setLayout(new MigLayout("", "[45%!][10%!][45%!]", ""));

		for (int i = 0; i < versioncolumnlen; i++) {
			String strdate = null;
			SimpleDateFormat dataformat = new SimpleDateFormat(
					"yyyy/MM/dd HH:mm:ss");
			if (versionarray[i * 2].getRevisionDate() != null) {
				strdate = dataformat.format(versionarray[i * 2]
						.getRevisionDate().getTime());
			}
			JVersionLabel label1 = new JVersionLabel("Version "
					+ versionarray[i * 2].getRevision() + " : " + strdate
					+ (versionarray[i * 2].isDeleted() ? " - deleted." : ""));
			label1.setVerticalAlignment(JButton.CENTER);
			label1.setFont(FONT);
			versionbuttonlist.add(label1);
			label1.addMouseListener(new LinkMouseListener(versionbuttonlist,
					i * 2, detailpanelparent));

			versionpanel.add(label1, "cell 0 " + i + " 1 1");
			versionlist.add(versionarray[i * 2]);

			if (i * 2 + 1 < versionarray.length) {
				strdate = dataformat.format(versionarray[i * 2 + 1]
						.getRevisionDate().getTime());
				JVersionLabel label2 = new JVersionLabel("Version "
						+ versionarray[i * 2 + 1].getRevision()
						+ " : "
						+ strdate
						+ (versionarray[i * 2 + 1].isDeleted() ? " - deleted."
								: ""));
				label2.setVerticalAlignment(JButton.CENTER);
				label2.setFont(FONT);
				label2.addMouseListener(new LinkMouseListener(
						versionbuttonlist, i * 2 + 1, detailpanelparent));
				versionpanel.add(label2, "cell 2 " + i + " 1 1");
				versionlist.add(versionarray[i * 2 + 1]);
				versionbuttonlist.add(label2);
			}

		}

		if (versionbuttonlist.size() > 0) {
			versionbuttonlist.get(versionbuttonlist.size() - 1).setSelect(true);
		}
	}

	private DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop,
			ClientPrimaryDataDirectory parentdir) {
		DefaultMutableTreeNode curDir = null;
		String parentname = "";
		try {
			curDir = new EdalMutableTreeModel(new EdalNode(parentdir.getName(),
					parentdir.getPath()));
			if (curTop != null) {
				curTop.add(curDir);
			}
			parentname = parentdir.getName();
			if (parentdir.isDirectory()) {
				List<ClientPrimaryDataEntity> dirlist = parentdir
						.listPrimaryDataEntities();
				List<String> dirnamelist = new ArrayList<String>();
				final Map<String, ClientPrimaryDataEntity> dirnamemap = new HashMap<String, ClientPrimaryDataEntity>();

				if (dirlist != null) {
					for (ClientPrimaryDataEntity dir : dirlist) {
						ClientPrimaryDataEntityVersion version = null;
						try {
							version = dir.getCurrentVersion();
							if (dir.isDirectory() && !(version.isDeleted())) {
								dirnamelist.add(dir.getName());
								dirnamemap.put(dir.getName(), dir);
							}
						} catch (Exception e) {
							// we don't have the permission to call
							// getCurrentVersion method
						}
					}
				}
				Collections.sort(dirnamelist, String.CASE_INSENSITIVE_ORDER);

				for (final String dirname : dirnamelist) {
					DefaultMutableTreeNode child = new EdalMutableTreeModel(
							new EdalNode(dirname,
									((ClientPrimaryDataDirectory) dirnamemap
											.get(dirname)).getPath()));
					curDir.add(child);
				}
			}
		} catch (RemoteException e) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(
					null,
					"Call remote Edal server function exception:"
							+ e.getMessage(), Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		} catch (PrimaryDataDirectoryException e) {
			ClientDataManager.logger.error(StackTraceUtil.getStackTrace(e));
			JOptionPane.showMessageDialog(null, "Can't load load all "
					+ parentname + " objects!", Const.EDAL_TITLE_STR,
					JOptionPane.ERROR_MESSAGE);
		}
		return curDir;
	}

	private class TableRowModelListener implements ListSelectionListener {
		private JTable table;
		private JPanel detailpanelparent;

		public TableRowModelListener(JTable table, JPanel detailpanelparent) {
			this.table = table;
			this.detailpanelparent = detailpanelparent;
		}

		public void valueChanged(ListSelectionEvent e) {
			isSelected = true;
			boolean b = table.getSelectionModel().getValueIsAdjusting();
			if (!b) {
				if (table.getSelectedRow() > -1) {
					selectrows = table.getSelectedRows();
					fileselectindex = table.getSelectedRow();
					if (selectrows.length == 1) {
						buildDetail(detailpanelparent,
								filelist.get(table.getSelectedRow()), true);
						try {
							pathtext.setText(filelist.get(
									table.getSelectedRow()).getPath());
						} catch (RemoteException e1) {
							ClientDataManager.logger.error(StackTraceUtil
									.getStackTrace(e1));
							JOptionPane.showMessageDialog(null,
									"Call remote Edal server function exception:"
											+ e1.getMessage(),
									Const.EDAL_TITLE_STR,
									JOptionPane.ERROR_MESSAGE);
						}
					} else {
						disablemetadata();
					}

					if (detailpanel != null) {
						if (!detailpanel.isCollapsed()) {
							detailpanel.setCollapsed(true);
							detailpanel.setScrollOnExpand(true);
						}
					}

				}
			}
		}

	}

	private void disablemetadata() {
		metadatabutton.setVisible(false);
		permissionbutton.setVisible(false);
		/*
		 * Component[] components = getComponents(metainfocontainer); for
		 * (Component component : components) { component.setEnabled(false); }
		 * metainfocontainer.setEnabled(false);
		 */
	}

	private Component[] getComponents(Component container) {
		ArrayList<Component> list = null;

		try {
			list = new ArrayList<Component>(
					Arrays.asList(((Container) container).getComponents()));
			for (int index = 0; index < list.size(); index++) {
				for (Component currentComponent : getComponents(list.get(index))) {
					list.add(currentComponent);
				}
			}
		} catch (ClassCastException e) {
			list = new ArrayList<Component>();
		}

		return list.toArray(new Component[list.size()]);
	}

	private void changemetadata(ClientPrimaryDataEntity dataentry,
			Map<EnumDublinCoreElements, UntypedData> metadatavalue,
			boolean refreshversion) {
		if (metadatavalue != null) {
			try {
				MetaData fileMetaData = dataentry.getMetaData().clone();
				Iterator iter = metadatavalue.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<EnumDublinCoreElements, UntypedData> entry = (Map.Entry<EnumDublinCoreElements, UntypedData>) iter
							.next();
					EnumDublinCoreElements key = entry.getKey();
					UntypedData val = entry.getValue();
					fileMetaData.setElementValue(key, val);

				}
				dataentry.setMetaData(fileMetaData);
				buildDetail(detailpanelparent, dataentry, refreshversion);

			} catch (Exception re) {
				ClientDataManager.logger
						.error(StackTraceUtil.getStackTrace(re));
				JOptionPane.showMessageDialog(null, re.getMessage(),
						Const.EDAL_TITLE_STR, JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private String formattooltips(String tooltips) {
		if (tooltips == null) {
			return "";
		}
		if (tooltips.length() <= TOOLTIPSLEN) {
			return tooltips;
		} else {
			return tooltips.substring(0, TOOLTIPSLEN) + "...";
		}
	}

	private WindowListener createAppCloser() {
		return new WindowAdapter() {
			@Override
			public void windowClosing(final WindowEvent we) {
				returnvalue = CANCEL_OPTION;
				dispose();
			}
		};
	}
}
